import React, { Component } from 'react'
import styles from "./cart.module.scss"
import { getCart, syncCart } from "../../data/api"
import empty from "../../assets/cart_empty.png"
import { withRouter } from "react-router-dom"
import { connect } from "react-redux"
import { Modal, Toast } from 'antd-mobile'
const alert = Modal.alert;
class Cart extends Component {
    state = {
        totalPrice: 0,//总价
        allChecked: false,//全选是否选中
        editChecked: false,//编辑管理
        goodsList: {},//购物车数据
        is_empty: true,//空   判断购物车是否为空的标志
        totalNum: 0,//购物车中的商品数量
        payCount: 0
    }
    async componentDidMount() {
        let res = await getCart();
        // console.log(res);
        if (res.meta.status === 200) {
            //获取购物车数据
            let cart_info = JSON.parse(res.message.cart_info);
            // console.log(JSON.parse(res.message.cart_info));
            //Object.values()返回一个数组，其元素是在对象上找到的可枚举属性值。属性的顺序与通过手动循环对象的属性值所给出的顺序相同
            let length = Object.values(cart_info).length
            //判断购物车是否为空
            if (length) {
                //给每件商品添加一个是否选中的标志
                for (let key in cart_info) {
                    cart_info[key].status = false;
                }
                this.setState({
                    goodsList: cart_info,
                    is_empty: false,
                    totalNum: length
                })
            }
        }

    }
    //同步购物车数据
    syncCartData = () => {
        syncCart({ infos: JSON.stringify(this.state.goodsList) });
        this.props.syncCartGoods(this.state.goodsList, this.state.totalPrice);
    }

    //处理编辑功能
    handleEidt = () => {
        this.setState({
            editChecked: !this.state.editChecked
        })
    }
    //处理全选问题
    handleAllCheck = (e) => {
        let obj = this.state.goodsList;
        // console.log(e.target.checked);
        //如果全选为选中状态，遍历goodsList，将每一个商品的状态都设置为true；否则全部设置为false
        for (let key in obj) {
            obj[key].status = e.target.checked
        }
        this.computeTotalPrice();
        this.setState({
            allChecked: e.target.checked,
            goodsList: obj,
            payCount: e.target.checked ? Object.values(this.state.goodsList).length : 0
        })
    }
    //判断是否全部选中
    isAllChecked = () => {
        let allChecked = true;
        let obj = this.state.goodsList;
        for (let key in obj) {
            if (!obj[key].status) {
                allChecked = false;
                break;
            }
        }
        this.setState({
            allChecked: allChecked
        })
    }
    //单个选中
    handleOneCheck = (index, e) => {
        // console.log(index);//index为goods_id,goodList的key值
        let obj = this.state.goodsList;
        // console.log(obj[index]);
        obj[index].status = e.target.checked;
        //判断列表是否全部选中
        this.isAllChecked();
        //计算价格
        this.computeTotalPrice();
        //重新设置状态
        this.setState({
            goodsList: obj,
            payCount: e.target.checked ? this.state.payCount + 1 : this.state.payCount - 1
        })
    }
    //计算总价
    computeTotalPrice = () => {
        // console.log("计算总价")
        let totalPrice = 0;
        let obj = this.state.goodsList;
        for (let key in obj) {
            // console.log(obj[key].status);
            if (obj[key].status) {
                totalPrice += obj[key].goods_price * obj[key].amount
            }
        }
        // console.log(totalPrice);
        this.setState({
            totalPrice,
        })
    }
    //商品减
    handleSub = (goods_id) => {
        // console.log(goods_id);
        let obj = this.state.goodsList;
        obj[goods_id].amount -= 1;
        this.setState({
            goodsList: obj
        }, () => {//setState的第二个参数，可以实现同步
            //同步购物车数据
            this.syncCartData();
            //计算价格
            this.computeTotalPrice();
            this.deleteGoods(goods_id);
        });
    }
    //商品加
    handleAdd = (goods_id) => {
        // console.log(goods_id);
        let obj = this.state.goodsList;
        obj[goods_id].amount += 1;
        this.setState({
            goodsList: obj
        }, () => {//setState的第二个参数，可以实现同步
            //同步购物车数据
            this.syncCartData();
            //计算价格
            this.computeTotalPrice();
        });
    }
    //单个删除删除商品
    deleteGoods = (index) => {
        let obj = this.state.goodsList;
        // console.log(index);
        //如果amount的值为0，就删除对应的商品
        if (obj[index].amount === 0) {
            delete obj[index];
        }
        this.setState({
            goodsList: obj,
            //如果购物车清空，重新设置购物车状态
            is_empty: Object.values(this.state.goodsList).length ? false : true,
        }, () => {
            this.syncCartData();
            this.computeTotalPrice();
        })
    }
    //批量删除
    handleRemove = () => {
        let obj = this.state.goodsList;
        for (let key in obj) {
            if (obj[key].status) {
                delete obj[key];
            }
        }
        this.setState({
            goodsList: obj,
            totalPrice: 0,
            is_empty: Object.values(this.state.goodsList).length ? false : true,
            payCount: 0,
            allChecked:false
        }, () => {
            this.syncCartData();
        })
    }
    //去结算
    goToPay = () => {
        if (!this.state.payCount) {
            Toast.info("你还没有选择要结算的商品", 1);
            return;
        }
        alert('结算','', [
            {
                text: '取消',
                style: {
                    backgroundColor: '#777',
                    color: '#fff',
                    fontWeight: 700
                }
            },
            {
                text: '确定',
                style: {
                    backgroundColor: 'rgb(244, 51, 60)',
                    color: '#fff',
                    fontWeight: 700
                },
                onPress:()=>{
                    this.props.history.push("/pay")
                }
            }
        ])
        // this.props.history.push("/pay");
        this.props.syncCartGoods(this.state.goodsList, this.state.totalPrice);
    }
    //跳转到详情页
    goToDetail = (goods_id) => {
        this.props.history.push("GoodDatail/" + goods_id);
        let obj = {};
        obj[goods_id] = this.state.goodsList[goods_id];
        // console.log(obj);
        //跳转的时候，要计算当前商品在购物车中有几个
        this.props.syncCartGoods(obj);
    }

    render() {
        return <div className={styles.brCart}>
            <div className={styles.header}>
                <div className={styles.title}>购物车</div>
                <div className={styles.edit} onClick={this.handleEidt}>{this.state.editChecked ? "完成" : "管理"}</div>
            </div>
            {/* 购物车内容开始 */}
            <div className={styles.content}>
                {
                    this.state.is_empty ?
                        // 购物车为空内容开始
                        < div className={styles.cartEmpty}>
                            <div className={styles.cartImg}>
                                <img src={empty} alt="" />
                            </div>
                            <p className={styles.cartTitle} >购物车是空的</p>
                            <div className={styles.cartBtn} onClick={() => {
                                // console.log(this.props);
                                this.props.history.push("/");
                            }}>去逛逛</div>
                        </div>
                        //物车为空内容结束
                        :
                        //购物车商品列表开始
                        <div className={styles.cartGoodsList}>
                            {
                                Object.values(this.state.goodsList).map((v, i) => {
                                    return <div className={styles.goodsListItem} key={v.goods_id}>
                                        <input type="checkbox" checked={v.status} onChange={this.handleOneCheck.bind(this, v.goods_id)} className={styles.oneCheck} />
                                        <div className={styles.goodsImg} onClick={this.goToDetail.bind(this, v.goods_id)}>
                                            <img src={v.goods_small_logo} alt="" />
                                        </div>
                                        <div className={styles.decribe}>
                                            <div className={styles.goodsTitle}>{v.goods_name}</div>
                                            <div className={styles.priceBox}>
                                                <p className={styles.price}>￥{v.goods_price}</p>
                                                <div className={styles.cartCompute}>
                                                    <button onClick={this.handleSub.bind(this, v.goods_id)}>-</button>
                                                    <span className={styles.goodsNum}>{v.amount}</span>
                                                    <button onClick={this.handleAdd.bind(this, v.goods_id)}>+</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                })
                            }
                        </div>
                    //购物车商品列表结束
                }
            </div>
            {/* 购物车内容结束 */}
            <div className={styles.footer}>
                <div className={styles.allCheck}>
                    <input type="checkbox" checked={this.state.allChecked} className={styles.check} onChange={this.handleAllCheck} />
            全选
          </div>
                <div>
                    {/* <div className={styles.total}>合计：￥{this.state.totalPrice}</div> */}
                    {
                        this.state.editChecked ? <div className={styles.delete} onClick={this.handleRemove}>删除</div>
                            : <div className={styles.countList}>
                                <div className={styles.total}>合计：￥{this.state.totalPrice}</div>
                                <div className={styles.count} onClick={this.goToPay} >结算 {this.state.payCount ? `(${this.state.payCount})` : ''}</div>
                            </div>
                    }
                </div>
            </div>
        </div >
    }
}
const mapDispacthToProps = (dispatch) => {
    return {
        syncCartGoods: (goodsList, totalPrice) => {
            dispatch({
                type: "SYNC_CART_GOODS",
                payload: {
                    goodsList: goodsList,
                    totalPrice: totalPrice
                }
            });
        }
    }
}
export default connect(null, mapDispacthToProps)(withRouter(Cart));
